<script setup>
import { ref } from 'vue';

const emit = defineEmits(['image-selected']);
const fileInput = ref(null);
const previewUrl = ref('');
const dragOver = ref(false);

const handleFileChange = (event) => {
  const file = event.target.files[0];
  if (file) {
    processFile(file);
  }
};

const handleDrop = (event) => {
  event.preventDefault();
  dragOver.value = false;
  const file = event.dataTransfer.files[0];
  if (file) {
    processFile(file);
  }
};

const processFile = (file) => {
  const reader = new FileReader();
  reader.onload = (e) => {
    previewUrl.value = e.target.result;
    emit('image-selected', file);
  };
  reader.readAsDataURL(file);
};
</script>

<template>
  <div class="bg-white rounded-xl shadow-sm p-6 min-h-[500px] flex flex-col">
    <h2 class="text-xl font-semibold mb-4 text-gray-800">上传图片</h2>
    <div
        class="flex-1 relative border-2 border-dashed rounded-xl p-8 text-center transition-all duration-200 flex items-center justify-center"
        :class="{
        'border-green-500 bg-green-50': dragOver,
        'border-gray-300 hover:border-green-500': !dragOver
      }"
        @click="fileInput.click()"
        @dragover.prevent="dragOver = true"
        @dragleave.prevent="dragOver = false"
        @drop="handleDrop"
    >
      <input
          type="file"
          ref="fileInput"
          @change="handleFileChange"
          accept="image/*"
          class="hidden"
      />

      <div v-if="!previewUrl" class="space-y-4">
        <div class="w-20 h-20 mx-auto rounded-full bg-green-100 flex items-center justify-center">
          <svg class="w-10 h-10 text-green-500" fill="none" stroke="currentColor" viewBox="0 0 24 24">
            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2"
                  d="M4 16l4.586-4.586a2 2 0 012.828 0L16 16m-2-2l1.586-1.586a2 2 0 012.828 0L20 14m-6-6h.01M6 20h12a2 2 0 002-2V6a2 2 0 00-2-2H6a2 2 0 00-2 2v12a2 2 0 002 2z"/>
          </svg>
        </div>
        <div>
          <p class="text-lg font-medium text-gray-700">放入食物图像</p>
          <p class="mt-1 text-sm text-gray-500">或单击以选择文件</p>
        </div>
      </div>

      <div v-else class="relative group w-full h-full flex items-center justify-center">
        <img :src="previewUrl" class="max-h-[350px] w-auto rounded-lg shadow-md" alt="Food preview"/>
        <div
            class="absolute inset-0 bg-black bg-opacity-40 opacity-0 group-hover:opacity-100 transition-opacity rounded-lg flex items-center justify-center">
          <p class="text-white">单击以更改图像</p>
        </div>
      </div>
    </div>
  </div>
</template>